﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using CONEK911Manager.DTO;

namespace CONEK911Manager.DAO
{
    class OrderDAO
    {
        readonly string _connectionString = ConfigurationManager.ConnectionStrings["Conek911ConnectionString"].ConnectionString;
        public bool AddOrder(OrderDTO order)
        {
            try
            {
                using (var con = new SqlConnection(_connectionString))
                {
                    const string sql = "INSERT into [Order] (Account, OrderDate) VALUES (@account, @orderdate)";
                    using (var sqlAddOrder = new SqlCommand(sql))
                    {
                        sqlAddOrder.Connection = con;
                        sqlAddOrder.Parameters.Add(new SqlParameter("@account", order.Account));
                        sqlAddOrder.Parameters.Add(new SqlParameter("@orderdate", order.OrderDate));
                        con.Open();
                        var result = sqlAddOrder.ExecuteNonQuery();
                        con.Close();
                        if (result == 1)
                        {
                            return true;
                        }
                        return false;
                    }
                }
            } catch (Exception e)
            {
                try
                {
                    Logger.WriteLog(e.Message + "-" + e.StackTrace);
                }
                catch
                { }
                return false;
            }
        }

        public List<OrderDTO> GetAllOrder()
        {
            var listOrder = new List<OrderDTO>();
            using (var con = new SqlConnection(_connectionString))
            {
                const string sql = "SELECT * FROM [Order]";
                using (var cmd = new SqlCommand(sql))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var order = new OrderDTO
                                              {
                                                  OrderId = int.Parse(Convert.ToString(reader["OrderID"])),
                                                  OrderDate = DateTime.Parse(Convert.ToString(reader["OrderDate"])),
                                                  Account = Convert.ToString(reader["Account"]),
                                              };
                            listOrder.Add(order);
                        }
                    }
                    con.Close();
                }
            }

            return listOrder;
        }
    }
}
